package com.ruben.study;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 并行流
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/9/14 15:18
 */
public class ParallelStreamDemo {
    public static void main(String[] args) {
        List<Integer> list = Stream.generate(() -> 1).limit(100).collect(Collectors.toList());
        System.out.println(list);
        int sum = list.parallelStream().reduce(1, Integer::sum, (a, b) -> {
            System.out.println(Thread.currentThread().getId() + " " + Thread.currentThread().getName() + " parallelStream执行sum时上次结果：[" + a + "]本次值：[" + b + "]");
            return Integer.sum(a, b);
        });
        Set<Long> threadIdSet = list.parallelStream().mapMultiToLong((i, c) -> c.accept(Thread.currentThread().getId())).collect(() -> Collections.synchronizedSet(new HashSet<>()), Set::add, Set::addAll);
        System.out.println("结果：" + sum);
        System.out.println("线程数：" + threadIdSet.size());
        System.out.println("Java 虚拟机可用的处理器数：" + Runtime.getRuntime().availableProcessors());
    }

}
